<template>
  <div>
    <div class="item">
      <div class="header">
        <span>描述</span>
      </div>
      <div class="content">
        <a-input
          v-model:value="props.nodeData.properties.remarks"
          :rows="3"
          placeholder="请输入描述"
          style="width: 100%"
          @change="setProperties()"
        />
      </div>
    </div>
    <div class="item">
      <div class="header">
        <span>输入变量</span>
      </div>
      <div class="content">
        <div class="var-item" v-for="(item, index) in inputParams" :key="index">
          <div class="name">
            <a-input v-model:value="item.name" @change="setProperties" placeholder="请输入变量名" />
          </div>
          <div class="field">
            <a-select style="width: 100%" v-model:value="item.id" placeholder="请选择输入字段" @change="handleFieldChange">
              <a-select-option v-for="preItem in prevVariables" :key="preItem.id" :value="preItem.id">
                {{ preItem.nodeName }}/{{ preItem.name }}
              </a-select-option>
            </a-select>
          </div>
          <div class="action">
            <DeleteOutlined @click="deleteItem(index)" />
          </div>
        </div>
      </div>
    </div>
    <div class="item">
      <a-button type="link" @click="addItem">+ 添加输入变量</a-button>
    </div>
    <div class="item">
      <div class="header">
        <span>模型</span>
      </div>
      <div class="content">
        <div style="display: flex; flex-direction: row; justify-content: center; align-items: center">
          <a-select style="width: 100%" v-model:value="model.modeId" placeholder="请选择模型" @change="handleModelChange">
            <a-select-option v-for="item in modelList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-popover placement="topLeft" :overlayStyle="{ width: '360px' }">
            <template #content>
              <a-form ref="userFormRef" :model="model" :rules="rules" class="user-form">
                <a-form-item label="模型温度" name="name">
                  <a-row>
                    <a-col :span="18">
                      <a-slider v-model:value="model.params.temperature" :step="0.1" :min="0" :max="1" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="model.params.temperature" :min="0" :max="1" />
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item label="词汇属性" name="modelType">
                  <a-row>
                    <a-col :span="18">
                      <a-slider v-model:value="model.params.topP" :step="0.1" :min="0" :max="1" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="model.params.topP" :min="0" :max="1" />
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item label="话题熟悉" name="modelName">
                  <a-row>
                    <a-col :span="18">
                      <a-slider v-model:value="model.params.presencePenalty" :step="0.1" :min="0" :max="1" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="model.params.presencePenalty" :min="0" :max="1" />
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item label="重复属性" name="baseUrl">
                  <a-row>
                    <a-col :span="18">
                      <a-slider v-model:value="model.params.frequencyPenalty" :step="0.1" :min="0" :max="1" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="model.params.frequencyPenalty" :min="0" :max="1" />
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item label="最大回复" name="baseUrl">
                  <a-row>
                    <a-col :span="18">
                      <a-slider v-model:value="model.params.maxTokens" :step="1" :min="0" :max="10000" />
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="model.params.maxTokens" :min="0" :max="10000" />
                    </a-col>
                  </a-row>
                </a-form-item>
              </a-form>
            </template>
            <icon-font iconClass="icon-opt-shezhi" color="#60666b" font-size="24px" />
          </a-popover>
        </div>
      </div>
    </div>
    <div class="item">
      <div class="header">
        <span>系统提示</span>
      </div>
      <div class="content">
        <a-dropdown :visible="showSystemDropdown" :trigger="dropdownTrigger">
          <a-textarea
            :rows="3"
            placeholder='请输入系统提示.按下"/"可选择变量'
            v-model:value="props.nodeData.properties.options.messages[0].content"
            style="width: 100%"
            @change="handleSystemTextArea"
            id="systemTextArea"
          />
          <template #overlay>
            <a-menu>
              <a-menu-item class="var-item" v-for="(item, index) in inputParams" :key="index" @click="handleSystemSelect(item.name)">
                <span>{{ item.name }}</span>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>
    <div class="item">
      <div class="header">
        <span>用户提示</span>
      </div>
      <div class="content">
        <a-dropdown :visible="showUserDropdown" :trigger="dropdownTrigger">
          <a-textarea
            :rows="3"
            placeholder='请输入用户提示.按下"/"可选择变量'
            v-model:value="props.nodeData.properties.options.messages[1].content"
            style="width: 100%"
         
               @change="handleUserTextArea"
            id="userTextArea"
          />
          <template #overlay>
            <a-menu>
              <a-menu-item class="var-item" v-for="(item, index) in inputParams" :key="index" @click="handleUserSelect(item.name)">
                <span>{{ item.name }}</span>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>
    <div class="item">
      <a-space>
        <span>保留</span>
        <a-input-number id="inputNumber" v-model:value="props.nodeData.properties.options.history" :min="1" :max="100" />
        <span>条历史记录</span>
      </a-space>
    </div>
    <div class="item">
      <div class="header">
        <span>输出变量</span>
      </div>
      <div class="content">
        <div style="display: flex; flex-direction: column">
          <span class="ai-label">{{ getOutputText }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue';
import { getPreNodes } from '../../../../utils/flowNodeUtils';
import { ModelApi } from '@/views/super/airag/aimodel/api/ModelApi';
const props = defineProps({
  nodeData: Object,
  lf: Object || String
});
const dropdownTrigger = ref(['click']);
const showSystemDropdown = ref(false);
const showUserDropdown = ref(false);


const model = ref(props.nodeData.properties?.options?.model);
const modelList = ref([]);
const prevNodes = ref([]);
const prevVariables = computed(() => {
  if (prevNodes.value.length === 0) return [];

  return prevNodes.value.flatMap(prevNode => {
    // 开始节点使用inputParams，其他节点使用outputParams
    const params = prevNode.type === 'start' ? prevNode.properties.inputParams : prevNode.properties.outputParams;

    var dd =
      Array.isArray(params) && params.length > 0
        ? params.map(param => ({
            nodeId: prevNode.id,
            nodeName: prevNode.properties.text,
            field: param.field,
            name: param.name,
            type: param.type,
            id: prevNode.id + '_' + param.field
          }))
        : [];
    console.log(dd);
    return dd;
  });
});

const getModelList = () => {
  let params = {
    pageNo: 0,
    pageSize: 1000,
    column: 'createTime',
    order: 'desc',
    modelType: 'LLM'
  };

  ModelApi.list(params).then(res => {
    if (res.success) {
      modelList.value = res.data.records;
    } else {
      modelList.value = [];
    }
  });
};
watch(
  () => props.nodeData,
  nodeDataChange => {
    console.log('nodeDataChange');
    var nodes = getPreNodes(props.nodeData, props.lf.graphModel);
    prevNodes.value = nodes;
    getModelList();
    console.log(nodes);
  },
  {
    immediate: true
  }
);

const handleFieldChange = value => {
  console.log(`selected ${value}`);
  setProperties();
};

const handleSystemTextArea = e => {
  if (e.data === '/') {
    showSystemDropdown.value = true;
    const textarea = document.querySelector('#systemTextArea');
    const textLength = textarea.value.length;
    if (textLength === 0) return; // 无文本时不操作

    // 设置选择范围：从最后一个字符开始，到末尾（即只选最后一个字符）
    textarea.focus(); // 获取焦点
    textarea.setSelectionRange(textLength - 1, textLength);
  } else {
    showSystemDropdown.value = false;
    setProperties();
  }
};
const handleUserTextArea = e => {
  if (e.data === '/') {
    showUserDropdown.value = true;
    const textarea = document.querySelector('#userTextArea');
    const textLength = textarea.value.length;
    if (textLength === 0) return; // 无文本时不操作

    // 设置选择范围：从最后一个字符开始，到末尾（即只选最后一个字符）
    textarea.focus(); // 获取焦点
    textarea.setSelectionRange(textLength - 1, textLength);
  } else {
    showUserDropdown.value = false;
    setProperties();
  }
};
const handleSystemSelect = value => {
  const textarea = document.querySelector('#systemTextArea');
  const cursorPosition = textarea.selectionStart;
  // 截取光标前的文本
  const startText = textarea.value.substring(0, cursorPosition);

  // 拼接文本，插入新内容
  // textarea.value = startText + '{{' + value + '}}';
  props.nodeData.properties.options.messages[0].content = startText + '{{' + value + '}}';
  console.log(props.nodeData.properties.options.messages[0].content);
  showSystemDropdown.value = false;
  // debugger;
};

const handleUserSelect = value => {
  const textarea = document.querySelector('#userTextArea');
  const cursorPosition = textarea.selectionStart;
  // 截取光标前的文本
  const startText = textarea.value.substring(0, cursorPosition);

  // 拼接文本，插入新内容
  // textarea.value = startText + '{{' + value + '}}';
  props.nodeData.properties.options.messages[1].content = startText + '{{' + value + '}}';
  console.log(props.nodeData.properties.options.messages[0].content);
  showUserDropdown.value = false;
  // debugger;
};

const handleModelChange = value => {
  debugger;
  var ml = modelList.value.find(item => item.id === value);
  if (ml) {
    console.log('ml.name' + ml.name);
    model.value.params.model = ml.name;
    // if (
    //   props.nodeData &&
    //   props.nodeData.properties &&
    //   props.nodeData.properties.options &&
    //   props.nodeData.properties.options.model
    // ) {
    //   props.nodeData.properties.options.model.modeId = value;
    //   props.nodeData.properties.options.model.params = model.params;
    // }
    console.log(props.nodeData.properties);
    setProperties();
  }
};
const inputParams = computed(() => {
  props.nodeData.properties.inputParams.forEach(item => {
    if (item.nodeId) {
      item.id = item.nodeId + '_' + item.field;
    }
  });
  return props.nodeData.properties.inputParams;
});
const getOutputText = computed(() => {
  return (
    props.nodeData.properties.outputParams[0].field +
    '<' +
    props.nodeData.properties.outputParams[0].type +
    '>' +
    props.nodeData.properties.outputParams[0].name
  );
});
const addItem = () => {
  props.nodeData.properties.inputParams.push({});
};
const deleteItem = index => {
  props.nodeData.properties.inputParams.splice(index, 1);
  setProperties();
};

const setProperties = () => {
  props.nodeData.properties.inputParams.forEach(item => {
    // if (item.nodeId) {
    //   item.id = item.nodeId + '_' + item.field;
    // }
    if (item.id) {
      var items = item.id.split('_');
      item.field = items[1];
      item.nodeId = items[0];
    }
  });
  props.lf.setProperties(props.nodeData.id, props.nodeData.properties);
};
</script>

<style lang='less' scoped>
.item {
  padding-top: 4px;
  padding-bottom: 4px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f0f0f0;
    border-radius: 4px;
    padding: 2px;
  }
  .content {
    background-color: #fff;
  }
}

.case-item {
  margin-bottom: 8px;
  position: relative;
}

.case-item .case-header {
  position: absolute;
  top: 1px;
  left: 1px;
  right: 11px;
  height: 30px;
  border-radius: 3px 0 0;
  background-color: #fff;
  z-index: 2;
  pointer-events: none;
  padding: 2px 11px;
  display: flex;
  justify-content: space-between;
}

.case-item .case-header .case-label {
  color: #999;
}

.case-item .case-header .case-action .app-iconify {
  cursor: pointer;
  pointer-events: auto;
}

.case-item .case-header .case-action .delete {
  transition: color 0.15s;
}

.case-item .case-header .case-action .delete:hover {
  color: #ff4d4f;
}

.case-item .case-input {
  padding-top: 32px;
}
.ai-label {
  color: rgb(170, 170, 170);
  font-size: 14px;
}

.var-item {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.var-item > div {
  margin-right: 10px;
}

.var-item > div:last-child {
  margin-right: 0;
}

.var-item > div.name,
.var-item > div.field {
  flex: 1;
}

.var-item > div.name .ant-input-disabled {
  color: #333 !important;
  cursor: default !important;
}

.var-item > div.action {
  margin-right: 0;
  text-align: center;
  width: 32px;
  height: 32px;
  line-height: 32px;
  cursor: pointer;
}

.var-item > div.action:hover {
  background-color: #f5f5f5;
}

.var-item > div > p {
  color: #e00;
  margin-top: 2px;
  margin-bottom: 0;
}
</style>